<?php

/**
 * medio_imagen actions.
 *
 * @package    hipermedio
 * @subpackage medio_imagen
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class medio_imagenActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    $this->medio_imagens = Doctrine_Core::getTable('MedioImagen')
      ->createQuery('a')
      ->execute();
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->medio_imagen = Doctrine_Core::getTable('MedioImagen')->findOneByNodoId(array($request->getParameter('nodo_id')));
    $this->forward404Unless($this->medio_imagen);
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new MedioImagenForm();
    $nodo_id = $request->getParameter('id');
    $this->nodo = Doctrine::getTable('Nodo')->findOneById($nodo_id);
    
    $ws = $this->form->getWidgetSchema();
    $ws['nodo_id']->setAttribute('value', $nodo_id);
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new MedioImagenForm();

    $medio = $this->processForm($request, $this->form);

    if($medio){
        return $this->renderPartial('show', array('medio' => $medio));
    }
    else{
        $this->setTemplate('new');
    }
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($medio_imagen = Doctrine_Core::getTable('MedioImagen')->find(array($request->getParameter('id'))), sprintf('Object medio_imagen does not exist (%s).', $request->getParameter('id')));
    $this->form = new MedioImagenForm($medio_imagen);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($medio_imagen = Doctrine_Core::getTable('MedioImagen')->find(array($request->getParameter('id'))), sprintf('Object medio_imagen does not exist (%s).', $request->getParameter('id')));
    $this->form = new MedioImagenForm($medio_imagen);

    $medio = $this->processForm($request, $this->form);

    if($medio){
        return $this->renderPartial('show', array('medio' => $medio));
    }
    else{
        $this->setTemplate('edit');
    }
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($medio_imagen = Doctrine_Core::getTable('MedioImagen')->find(array($request->getParameter('id'))), sprintf('Object medio_imagen does not exist (%s).', $request->getParameter('id')));
    $medio_imagen->delete();

    $this->redirect('medio_imagen/index');
  }
  
  public function executeUpload(sfWebRequest $request) {
        
        $error = "";
        $msg = "";
        $file = $request->getFiles('fileToUpload');
        $nodo_uuid = $request->getParameter('id');
        
        if (!empty($file['error'])) {
            switch ($file['error']) {

                case '1':
                    $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;
                case '2':
                    $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    break;
                case '3':
                    $error = 'The uploaded file was only partially uploaded';
                    break;
                case '4':
                    $error = 'No file was uploaded.';
                    break;
                case '6':
                    $error = 'Missing a temporary folder';
                    break;
                case '7':
                    $error = 'Failed to write file to disk';
                    break;
                case '8':
                    $error = 'File upload stopped by extension';
                    break;
                case '999':
                default:
                    $error = 'No error code avaiable';
            }
        } elseif (empty($file['tmp_name']) || $file['tmp_name'] == 'none') {
            $error = 'Ningún archivo fue subido..';
        } else {
            $msg .= " Nombre del archivo: " . $file['name'] . "</br>";
            $msg .= " Tamaño del archivo: " . @filesize($file['tmp_name']);
            
            
            // Vemos la extension del archivo
            $partes_ruta = pathinfo($file['name']);
            $extension = $partes_ruta['extension'];
            $name = $nodo_uuid.'.'.$extension;
            
            // Ruta donde guardamos el archivo
            $dest = sfConfig::get('sf_upload_dir').'/images/'.$name;
            
            // Guardamos la imagen
            move_uploaded_file($file['tmp_name'], $dest);
            
            // Modificamos las dimensiones de la foto
            try {
                $img = new sfImage($dest, 'image/jpg');
                if ($img->getWidth() > 500 || $img->getHeight() > 300) {
                    if ($img->getWidth() > $img->getHeight()) {
                        $img->resize(500, null);
                    } else {
                        $img->resize(null, 300);
                    }
                    $img->save();
                }
            } catch (Exception $e) {
                $error = 'Excepción capturada: '.$e->getMessage()."\n";
            }
            
            //for security reason, we force to remove all uploaded file
            @unlink($file);   
        }
        
        $s = "{";
        $s .= "error: '" . $error . "',\n";
        $s .= "msg: '" . $msg . "',\n";
        $s .= "name: '" . $name . "'\n";
        $s .= "}";
        
        return $this->renderText($s);
    }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $medio_imagen = $form->save();
      
      $nodo = $medio_imagen->getNodo();
      $nodo->setTipoMedio('imagen');
      $nodo->save();
      
      if($medio_imagen->getCodigo() != null && $medio_imagen->getOpcion() != 'archivo'){
          
          // Copiamos la imagen al servidor
          try {
            $url = $medio_imagen->getCodigo();
            $partes_ruta = pathinfo($url);
            $dest = sfConfig::get('sf_upload_dir'). DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $nodo->getUuid() . '.' .$partes_ruta['extension'];
            copy($url, $dest);
          } 
          catch (Exception $e) {
            echo 'Excepción capturada: ',  $e->getMessage(), "\n";
          }
          
          // Actualizamos la ruta
          $medio_imagen->setFuente($nodo->getUuid() . '.' .$partes_ruta['extension']);
          $medio_imagen->save();
          
          // Vemos las dimensiones de la foto
          try {
              
            $img = new sfImage($dest, 'image/jpg');
            if($img->getWidth() > 500 || $img->getHeight() > 300){
              if($img->getWidth() > $img->getHeight()){
                  $img->resize(500,null);
              }
              else{
                  $img->resize(null,300);
              }
              $img->save();
            }
          } 
          catch (Exception $e) {
            echo 'Excepción capturada: ',  $e->getMessage(), "\n";
          }
      }
      
      return $medio_imagen;
//      $this->redirect('nodo/show?id='.$medio_imagen->getNodoId());
    }
  }
}
